package com.rmondjone.face

import android.content.Intent
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.rmondjone.androidcamerademo.R
import com.rmondjone.androidcamerademo.bean.SuggestBean
import com.rmondjone.face.ViewModel.FaceViewModel
import com.rmondjone.face.adapter.SuggestAdapter
import kotlinx.android.synthetic.main.activity_face.recyclerview
import kotlinx.android.synthetic.main.frgment_suggest.*
import kotlinx.android.synthetic.main.item_title.view.*

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */
class SuggestFragment : Fragment() {


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.frgment_suggest, container, false)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val get = ViewModelProviders.of(requireActivity()).get(FaceViewModel::class.java)

        initWebView()

        recyclerview.apply {

            layoutManager = LinearLayoutManager(requireContext())
            val suggestAdapter = SuggestAdapter()
            adapter = suggestAdapter
            get.faceConsultBean.value?.tiaoli?.apply {


                if (!TextUtils.isEmpty(aiteimoth)) {
                    layout_aijiu.visibility = View.VISIBLE
                    layout_aijiu.tv_title.text = "艾贴方法"
                    mWebView.loadDataWithBaseURL(null, aiteimoth, "text/html", "utf-8", null);//加载html数据
                } else {
                    mWebView.visibility = View.GONE
                }

                val arrayListOf = arrayListOf<SuggestBean>()
                arrayListOf.apply {
//                    add("艾灸方法", aiteimoth)
                    add("经络保健", jingluobaojian)
                    add("食疗", shiliao)
                    add("精神调养", jingshentiaoyang)
                    add("体育锻炼", tiyuduanlian)
                    add("起居调摄", qijutiaoshe)
                    add("音乐调理", yinyuetiaoli)
                    add("适宜食物", shiyishiwu)
                    add("适宜运动", shiyiyundong)
                }
                suggestAdapter.setNewData(arrayListOf)


            }
        }


    }


    private fun initWebView() {
        val setting: WebSettings = mWebView.settings
        // 支持缩放
        // 支持缩放
        setting.setSupportZoom(false)
        // 设置支持缩放 + -
        // 设置支持缩放 + -
        setting.builtInZoomControls = true
        // 关闭 webView 中缓存
        /**/
        /*webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);*/
        // 关闭 webView 中缓存
        /**/
        setting.useWideViewPort =
                true
        setting.loadWithOverviewMode = true
        // 设置WebView属性，能够执行Javascript脚本
        // 设置WebView属性，能够执行Javascript脚本
        setting.javaScriptEnabled = true
        setting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        setting.savePassword = false
        setting.domStorageEnabled = true
        setting.allowFileAccess = true
        setting.defaultTextEncodingName = "utf-8"
        // 设置UserAgent
        // 设置UserAgent
        setting.blockNetworkImage = false // 解决图片不显示

        setting.displayZoomControls = false

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }


        mWebView.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler, error: SslError?
            ) {
                handler.proceed() // 接受证书
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {

                if (url.isNullOrEmpty()) {
                    return false
                }
                try {
                    // 处理自定义scheme协议
                    if (!url.startsWith("http") && !url.startsWith("https")) {
                        return try {
                            val intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                            intent.flags =
                                    Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                            intent.addCategory("android.intent.category.BROWSABLE")
                            intent.component = null
                            if (null != intent) {
                                startActivity(intent)
                            }
                            true
                        } catch (e: Exception) {
                            // 没有安装的情况
                            e.printStackTrace()
                            //                            ToastUitl.showShort("尚未安装此应用！");
                            true
                        }
                    }

                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                return super.shouldOverrideUrlLoading(view, url)

            }


        }

        mWebView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                if (title.isNullOrEmpty()) {
                    return
                }
//                tv_title.text = title
            }

            override fun onProgressChanged(
                    view: WebView?,
                    newProgress: Int
            ) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
//                    mProgression.visibility = View.GONE
                } else {
//                    mProgression.visibility = View.VISIBLE
//                    mProgression.progress = newProgress //设置加载进度
                }
            }

        }
        mWebView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->

        }
    }
}


fun ArrayList<SuggestBean>.add(title: String, content: String?) {

    if (!content.isNullOrEmpty()) {
        add(SuggestBean(title, content))
    }

}

